﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace ValidationFramework.WPF
{
	/// <summary>
	/// A <see cref="IValueConverter"/> for converting between <see cref="bool"/>s and <see cref="object"/>s.
	/// </summary>
	#if (!SILVERLIGHT)
	[ValueConversion(typeof(bool), typeof(object))]
#endif
	public class ObjectToBoolConverter : IValueConverter
	{
        /// <inheritdoc />
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
		    if (targetType != typeof (bool) && targetType != typeof (bool?))
		    {
		        throw new ArgumentException("Type must be a bool", "targetType");
		    }
        	bool returnValue;
			if (value == null)
			{
				returnValue = (value == parameter);
			}
			else
			{
			  var type = value.GetType();
        if (type.IsEnum && (parameter is string))
        {
        	parameter = Enum.Parse(type, (string) parameter, true);
        }
				returnValue = value.Equals(parameter);
			}
          if (Negate)
			{
				returnValue = !returnValue;
			}
        	return returnValue;
		}
		public bool Negate { get; set; }

        /// <inheritdoc />
		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if (Negate)
			{
				throw new InvalidOperationException("Can not ConvertBack with Negate=true.");
			}
			return  parameter;
		}
	}
}
